package com.google.code.crawler.tools;

import java.io.IOException;

import org.jsoup.Connection;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import com.google.code.crawler.util.CrawlerUtils;

@Service("documentHandler")
public class DocumentHandler
{
    private static final Logger LOGGER = LoggerFactory.getLogger(DocumentHandler.class);

    public Document getDocument(final String URL)
    {

        Document result = null;

        if (URL != null && !URL.isEmpty())
        {

            final Connection connection = Jsoup.connect(URL);

            if (connection != null)
            {
                try
                {
                    result = connection.get();
                } catch (IOException ioe)
                {
                    LOGGER.error("Error opening connection, IOException..." + ioe.getMessage());
                }

            }

        }

        return result;
    }

    public Elements getElements(final String elementName, final Document document)
    {

        Elements result = null;

        if (document != null && document.hasText() && !CrawlerUtils.isNullOrEmpty(elementName))
        {
            result = document.select(elementName);
        }

        return result;

    }

}
